package com.example.easyexceldemo.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * List工具类
 * 
 */
public class ListUtil {

	/**
	 * List 分页
	 * 
	 * @param list     数据源
	 * @param pageSize 每页大小
	 * @return List<List<T>> 嵌套的List,内部List是每页数据
	 */
	public static <T> List<List<T>> paging(Collection<T> list, int pageSize) {
		int totalCount = list.size();
		int pageCount;
		int m = totalCount % pageSize;

		if (m > 0) {
			pageCount = totalCount / pageSize + 1;
		} else {
			pageCount = totalCount / pageSize;
		}
		List<T> orgList = null;
		if (list instanceof List) {
			orgList = (List<T>) list;
		} else {
			orgList = new ArrayList<>(list);
		}
		List<List<T>> totalList = new ArrayList<List<T>>();
		for (int i = 1; i <= pageCount; i++) {
			if (m == 0) {
				List<T> subList = orgList.subList((i - 1) * pageSize, pageSize * (i));
				totalList.add(subList);
			} else {
				if (i == pageCount) {
					List<T> subList = orgList.subList((i - 1) * pageSize, totalCount);
					totalList.add(subList);
				} else {
					List<T> subList = orgList.subList((i - 1) * pageSize, pageSize * i);
					totalList.add(subList);
				}
			}
		}
		return totalList;
	}

}